/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution 
{
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) 
    {
        vector<vector<int>> ret;
        if (root == nullptr)
        {
            return ret;
        }

        queue<TreeNode*> treeQueue;
        treeQueue.push(root);
        bool IsLeftFirst = true;

        while (!treeQueue.empty())
        {
            int Size = treeQueue.size();
            deque<int> levelList;
            for (size_t i = 0; i < Size; i++)
            {
                TreeNode* node = treeQueue.front();
                treeQueue.pop();                           // 队首元素出栈      
                if (IsLeftFirst)
                {
                    levelList.push_back(node->val);
                }
                else
                {
                    levelList.push_front(node->val);
                }

                if (node->left)
                {
                    treeQueue.push(node->left);
                }
                if (node->right)
                {
                    treeQueue.push(node->right);
                }
            }
            ret.push_back(vector<int>(levelList.begin(), levelList.end()));
            IsLeftFirst = !IsLeftFirst;
        }
        return ret;
        
    }
};